/**
 * 排班表主组件
 * 这是用户实际使用的组件入口
 */

import { useEffect, useRef, useState } from 'react'
import type { Employee, Shift, Plugin, ScheduleConfig, ScheduleContext } from './types'
import { ScheduleCore } from './core/ScheduleCore'
import './styles/index.css'

export interface ScheduleProps {
  /** 初始员工数据 */
  employees?: Employee[]
  /** 初始班次数据 */
  shifts?: Shift[]
  /** 插件列表 */
  plugins?: Plugin[]
  /** 配置选项 */
  config?: ScheduleConfig
  /** 类名 */
  className?: string
  /** 样式 */
  style?: React.CSSProperties
}

/**
 * 排班表组件
 * 可以通过插件系统扩展任何功能
 */
export function Schedule({
  employees = [],
  shifts = [],
  plugins = [],
  config = {},
  className = '',
  style = {},
}: ScheduleProps) {
  const coreRef = useRef<ScheduleCore | null>(null)
  const [context, setContext] = useState<ScheduleContext | null>(null)
  const [enabledPlugins, setEnabledPlugins] = useState<Plugin[]>([])
  const [isReady, setIsReady] = useState(false)

  // 初始化核心实例（只在组件挂载时执行一次）
  useEffect(() => {
    const core = new ScheduleCore(config)
    coreRef.current = core

    // 初始化数据
    employees.forEach(emp => core.getStateManager().addEmployee(emp))
    shifts.forEach(shift => core.getStateManager().addShift(shift))

    // 安装插件
    const initPlugins = async () => {
      try {
        await core.installPlugins(plugins)
        setEnabledPlugins(core.getEnabledPlugins())
        setContext(core.getContext())
        setIsReady(true)
      } catch (error) {
        console.error('Failed to initialize plugins:', error)
      }
    }

    initPlugins()

    // 清理
    return () => {
      core.destroy()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 监听外部数据变化，同步到核心
  useEffect(() => {
    if (!coreRef.current || !isReady) return

    const core = coreRef.current
    const stateManager = core.getStateManager()

    // 同步员工数据
    const currentEmployees = stateManager.getEmployees()
    if (employees.length > 0 && currentEmployees.length === 0) {
      employees.forEach(emp => stateManager.addEmployee(emp))
    }

    // 同步班次数据
    const currentShifts = stateManager.getShifts()
    if (shifts.length > 0 && currentShifts.length === 0) {
      shifts.forEach(shift => stateManager.addShift(shift))
    }
  }, [employees, shifts, isReady])

  // 监听插件变化（只在组件挂载时执行一次）
  useEffect(() => {
    if (!coreRef.current) return

    const core = coreRef.current
    const unsubscribe = core.getEventBus().on('plugin:*', () => {
      setEnabledPlugins(core.getEnabledPlugins())
    })

    return unsubscribe
  }, [])

  // 等待初始化完成
  if (!isReady || !context) {
    return (
      <div className={`schedule-loading ${className}`} style={style}>
        <div className="loading-spinner">Loading...</div>
      </div>
    )
  }

  return (
    <div className={`schedule-container ${className}`} style={style}>
      {/* 渲染所有启用的插件组件 */}
      {enabledPlugins.map(plugin => {
        if (plugin.component) {
          const PluginComponent = plugin.component
          return <PluginComponent key={plugin.id} context={context} />
        }
        return null
      })}

      {/* 如果没有插件，显示提示 */}
      {enabledPlugins.length === 0 && (
        <div className="schedule-empty">
          <p>No plugins installed</p>
          <p>Please add plugins to display the schedule</p>
        </div>
      )}
    </div>
  )
}
